package main

import (
	"fmt"
	"sync"
	"time"

	"git.dev.tencent.com/lwch/runtime"
)

type blockingValueType struct {
	c *client
	t time.Time
}

type blockingType struct {
	sync.RWMutex
	data map[string]blockingValueType
}

var blocking = blockingType{data: make(map[string]blockingValueType)}

func (b *blockingType) begin(c *client, idx, offset int) {
	key := fmt.Sprintf("%d/%d", idx, offset)
	b.Lock()
	b.data[key] = blockingValueType{c, time.Now()}
	b.Unlock()
}

func (b *blockingType) done(idx, offset int) {
	key := fmt.Sprintf("%d/%d", idx, offset)
	b.Lock()
	delete(b.data, key)
	b.Unlock()
}

func (b *blockingType) isBlocking(idx, offset int) bool {
	key := fmt.Sprintf("%d/%d", idx, offset)
	b.RLock()
	d, ok := b.data[key]
	b.RUnlock()
	if !ok {
		return false
	}
	if time.Since(d.t).Seconds() > 60 {
		d.c.ignore()
		b.Lock()
		delete(b.data, key)
		b.Unlock()
		runtime.Log("%d/%d is timeout", idx, offset)
		return false
	}
	runtime.Log("%d/%d is blocking", idx, offset)
	return true
}
